package com.yunhoo.govProcure.bean;

import com.ibatis.dao.client.DaoManager;
import com.yunhoo.base.model.Category;
import com.yunhoo.base.model.Department;
import com.yunhoo.base.model.FinancialProject;
import com.yunhoo.base.model.Person;
import com.yunhoo.checkFlow.db.dao.FlowInfoDao;
import com.yunhoo.checkFlow.model.FlowInfo;
import com.yunhoo.checkFlow.util.BillType;
import com.yunhoo.govProcure.db.dao.ProcureExecEditDao;
import com.yunhoo.govProcure.db.dao.ProcurePlanEditDao;
import com.yunhoo.govProcure.model.CateDataModel;
import com.yunhoo.govProcure.model.CateEditBase;
import com.yunhoo.govProcure.model.CateEditDetail;
import com.yunhoo.govProcure.model.ExecuteAppend;
import com.yunhoo.sys.db.config.DaoConfig;
import com.yunhoo.sys.db.util.IbatisTemplate;
import com.yunhoo.sys.util.common.CommonParam;
import com.yunhoo.sys.util.common.LoginParam;
import com.yunhoo.sys.util.common.NavigationTool;
import com.yunhoo.sys.util.common.Null;
import com.yunhoo.sys.util.tree.TreeUtil;
import java.io.Serializable;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.faces.model.SelectItem;
import org.richfaces.event.TreeSelectionChangeEvent;

@ManagedBean(name = "executCheckBean")
@SessionScoped
public class ProcureExecCheckBean implements Serializable {

    private final static DaoManager daom = DaoConfig.getDaoManager();
    private static FlowInfoDao flowInfoDao = (FlowInfoDao) daom.getDao(FlowInfoDao.class);
    private static ProcureExecEditDao editDao = (ProcureExecEditDao) daom.getDao(ProcureExecEditDao.class);
    //
    private CateEditBase base = null;
    private CateEditDetail detail = null;
    private DataModel<CateEditDetail> detailModel = new ListDataModel<CateEditDetail>();
    private Integer iyear = 0;
    private List<Integer> yearli = CommonParam.yearListOfInteger();
    private String quality = "";//采购计划资金性质
    private List<SelectItem> selectNameli;
    private List<FinancialProject> projList = new ArrayList<FinancialProject>();
    private DataModel<FinancialProject> projModel = new ListDataModel<FinancialProject>();
    private boolean addOrUpdate = false;
    private boolean editStatus = false;
    private boolean checkStatus = false;
    private List<String> itemli = new ArrayList<String>();
    private Category cate = new Category();
    private FlowInfo currennode = new FlowInfo(true);
    private Integer curIndex = -1;
    private List<CateEditDetail> detailli = new ArrayList<CateEditDetail>();
    private LinkedList<CateEditDetail> linkedli = new LinkedList<CateEditDetail>();
    private ExecuteAppend exappend = new ExecuteAppend();
    private Integer isession = 0;
    private Integer isessionFor = 0;
    private List<CateEditDetail> viewList = null;

    public ProcureExecCheckBean() {
    }

    public void yearChange() {
        initSession();
    }

    private void initSession() {
        Calendar calendar = Calendar.getInstance();

        int sysYear = calendar.get(Calendar.YEAR);
        int sysMonther = calendar.get(Calendar.MONTH) + 1;

        System.out.println("sysYear : " + sysYear);
        System.out.println("sysMonther : " + sysMonther);

        if (iyear > sysYear) {
            System.out.println("系统时间错误！");
            isessionFor = 0;
        } else if (iyear < sysYear) {
            isessionFor = 4;
            System.out.println("iyear < sysYear");
        } else if (iyear == sysYear) {
            Integer imonth = sysMonther;
            System.out.println("imonth:" + imonth);
            if (imonth >= 1 && imonth <= 3) {
                isessionFor = 1;
            } else if (imonth >= 4 && imonth <= 6) {
                isessionFor = 2;
            } else if (imonth >= 7 && imonth <= 9) {
                isessionFor = 3;
            } else if (imonth >= 10 && imonth <= 12) {
                isessionFor = 4;
            }
        }
    }

    private void initStatus() {
        addOrUpdate = false;
        editStatus = false;
    }

    public void initProjList() {
        projList = CommonParam.financialProjectList();
        projModel.setWrappedData(projList);
    }

    public void intiItemLi() {
        itemli = editDao.queryAllCategroyStandardCode();
    }

    public void selectProject() {
        FinancialProject proj = projModel.getRowData();
        detail.setProject(proj);
    }

    public void cateSelected(TreeSelectionChangeEvent event) {
        cate = (Category) TreeUtil.listener(event);
        detail.setCate(cate);
        List<CateDataModel> list = new ArrayList<CateDataModel>();
        for (String item : itemli) {
            if (cate.getCode().trim().startsWith(item.trim())) {
                list = editDao.queryCategroyStandardByCategoryCode(item.trim());
            }
            if (cate.getCode().trim().startsWith(item.trim())) {
                list = editDao.queryCategroyStandardByCategoryCode(item.trim());
            }
            if (cate.getCode().trim().startsWith(item.trim())) {
                list = editDao.queryCategroyStandardByCategoryCode(item.trim());
            }
            selectNameli = new ArrayList<SelectItem>();
            for (CateDataModel l : list) {
                selectNameli.add(new SelectItem(l.getItemCode(), l.getSelectName()));
            }
        }
    }

    public void query() {
        detailli.clear();
        linkedli.clear();
//        Map map = new HashMap();
//        map.put("imonth", isession);
//        map.put("iyear", iyear);
//        List<CateEditBase> exebaseli = dao.queryList02(map, NAMESPACE);
        CateEditBase param = new CateEditBase(true);
        param.setImonth(isession);
        param.setIyear(iyear);
        List<CateEditBase> exebaseli = editDao.queryListCateBase(param);
        if (!Null.check(exebaseli)) {
            for (CateEditBase planbase : exebaseli) {
//                map.put("number", planbase.getNumber());
//                map.put("quality", quality);
//                map.put("status", "0");
//                List<CateEditDetail> exelist = dao.queryList(map, NAMESPACE);

                CateEditDetail param1 = new CateEditDetail();
                param1.setOrgCode(LoginParam.getOrg().getCode());
                param1.setIyear(iyear);
                param1.setNumber(planbase.getNumber());
                param1.setQuality(quality);
                param1.setStatus("0");
                List<CateEditDetail> exelist = editDao.queryListCateDetailForCheck(param1);
                detailli.addAll(exelist);
            }
            detailModel.setWrappedData(detailli);
            linkedli.addAll(detailli);
        }
    }

    public void queryList() {
        if (Null.check(iyear)) {
            System.out.println("请选择年度!");
        } else if (Null.check(isession)) {
            System.out.println("请选择季度!");
        } else {
            query();
            initStatus();
        }
    }

    public void selectdExAppend() {
        detail = detailModel.getRowData();
        // exappend = (ExecuteAppend) dao.query03(detail.getAnumber().trim(), NAMESPACE);
        ExecuteAppend param = new ExecuteAppend(true);
        param.setAnumber(detail.getAnumber());
        exappend = editDao.queryExecuteAppend(param);
    }

    public void selectdAppend() {
        //exappend = (ExecuteAppend) dao.query03(detail.getAnumber().trim(), NAMESPACE);
        ExecuteAppend param = new ExecuteAppend(true);
        param.setAnumber(detail.getAnumber());
        exappend = editDao.queryExecuteAppend(param);
    }

    public void selected() {
        detail = detailModel.getRowData();
        if (!Null.check(detail.getCheckNumber())) {
            //currennode = (FlowInfo) dao.query(detail.getCheckNumber().trim(), NAME_SPACE);
            FlowInfo param = new FlowInfo(true);
            param.setNumber(String.valueOf(detail.getId()));
            param.setType(BillType.PROCURE_EXEC);
            List<FlowInfo> li = flowInfoDao.queryFlowInfoByNumberAndType(param);
            if (li != null) currennode = li.get(0);
            checkStatus = true;
            System.out.println("currennode1: " + currennode);
        } else {
            currennode = new FlowInfo(true);
            currennode.setCheckerName(getCurPer().getCpsn_name().trim());
            checkStatus = false;
            System.out.println("currennode2: " + currennode);
        }
        System.out.println("detail: " + detail.getCheckNumber());
        NavigationTool.getSelectedUrl("/page/govProcure/check/executGovCheck.xhtml");
    }

    public void selectedFromView(CateEditDetail row) {
        detail = row;
        if (!Null.check(detail.getCheckNumber())) {
            //currennode = (FlowInfo) dao.query(detail.getCheckNumber().trim(), NAME_SPACE);
            FlowInfo param = new FlowInfo(true);
            param.setNumber(String.valueOf(detail.getId()));
            param.setType(BillType.PROCURE_EXEC);
            List<FlowInfo> li = flowInfoDao.queryFlowInfoByNumberAndType(param);
            if (li != null) currennode = li.get(0);
            checkStatus = true;
            System.out.println("currennode1: " + currennode);
        } else {
            currennode = new FlowInfo(true);
            currennode.setCheckerName(getCurPer().getCpsn_name().trim());
            checkStatus = false;
            System.out.println("currennode2: " + currennode);
        }
        System.out.println("detail: " + detail.getCheckNumber());
        NavigationTool.getSelectedUrl("/page/govProcure/check/executGovCheck.xhtml");
    }

    public void check() throws SQLException {
        if (!Null.check(currennode.getIsConfirm())) {
            currennode.setNumber(String.valueOf(detail.getId()));
            currennode.setChecker(getCurPer().getCpsn_number().trim());
            currennode.setType(BillType.PROCURE_EXEC);
            currennode.setCheckLevel(0);
            //dao.insert(currennode, NAME_SPACE);
            flowInfoDao.insertFlowInfo(currennode);
            if (currennode.getIsConfirm().equals("1")) {
                detail.setStatus("3");
                detail.setCheckNumber(currennode.getNumber().trim());
                // dao.update03(detail, NAMESPACE);
                editDao.updateExecDetail(detail);
            } else {
                detail.setStatus("2");
                detail.setCheckNumber(currennode.getNumber().trim());
                //dao.update03(detail, NAMESPACE);
                editDao.updateExecDetail(detail);
            }
            checkStatus = true;
            System.out.println("审批完成!");
        } else {
            System.out.println("请选择是否同意!");
        }
    }

    public void canclCheck() throws SQLException {
        if (detail.getStatus().equals("3")) {
            // dao.delete(detail.getCheckNumber().trim(), NAME_SPACE);
            /* 删除相关审批信息
             FlowInfo param = new FlowInfo(true);
             param.setNumber(detail.getCheckNumber());
             flowInfoDao.deleteFlowInfoByNumber(param);
             */
            detail.setStatus("1");
            detail.setCheckNumber("");
            // dao.update03(detail, NAMESPACE);
            editDao.updateExecDetail(detail);
            currennode = new FlowInfo(true);
            currennode.setCheckerName(getCurPer().getCpsn_name().trim());
            checkStatus = false;
        }
    }

    public void first() {
        if (!Null.check(linkedli)) {
            detail = linkedli.getFirst();
            curIndex = 0;
            selectDetail();
        } else {
            System.out.println("没有数据!");
        }
    }

    public void last() {
        if (!Null.check(linkedli)) {
            detail = linkedli.getLast();
            curIndex = linkedli.size() - 1;
            selectDetail();
        } else {
            System.out.println("没有数据!");
        }
    }

    public void previou() {
        Integer index = -1;
        if (!Null.check(linkedli)) {
            index = linkedli.indexOf(detail);
        }
        if (index > 0) {
            detail = linkedli.get(index - 1);
            curIndex = index - 1;
            selectDetail();
        } else {
            System.out.println("没有了!");
        }
    }

    public void next() {
        Integer index = -1;
        if (!Null.check(linkedli)) {
            index = linkedli.indexOf(detail);
        }
        if (index > -1 && index < linkedli.size() - 1) {
            detail = linkedli.get(index + 1);
            curIndex = index + 1;
            selectDetail();
        } else {
            System.out.println("没有了!");
        }
    }

    public void selectDetail() {
        List<CateDataModel> list = new ArrayList<CateDataModel>();
        if (!Null.check(detail.getCheckNumber())) {
            //currennode = (FlowInfo) dao.query(detail.getCheckNumber().trim(), NAME_SPACE);
            FlowInfo param = new FlowInfo(true);
            param.setNumber(String.valueOf(detail.getId()));
            param.setType(BillType.PROCURE_EXEC);
            List<FlowInfo> li = flowInfoDao.queryFlowInfoByNumberAndType(param);
            if (li != null) currennode = li.get(0);
            checkStatus = true;
            System.out.println("currennode1: " + currennode);
        } else {
            currennode = new FlowInfo(true);
            currennode.setCheckerName(getCurPer().getCpsn_name().trim());
            checkStatus = false;
            System.out.println("currennode2: " + currennode);
        }
        System.out.println("detail: " + detail.getCheckNumber());
    }

    public void goback() {
        NavigationTool.getSelectedUrl("/page/govProcure/check/executGovCheckLi.xhtml");
    }

    public void contentListener() {
        if (currennode.getIsConfirm().equals("1")) {
            currennode.setContent("同意");
        }
        if (currennode.getIsConfirm().equals("2")) {
            currennode.setContent("不同意");
        }
    }

    public String maxCode() {
        Integer maxCode = flowInfoDao.queryMaxNumber(new FlowInfo(true));
        return String.format("%05d%n", (maxCode == null ? 0 : maxCode) + 1).trim();
    }

    public void initViewList() {
        System.out.println(" * * * " + "init exec viewList !" + "  * * * ");

        Map map = new HashMap();
        map.put("orgCode", LoginParam.getOrg().getCode());
        map.put("yearSys", LoginParam.getIyear());
        map.put("yearQuery", null);
        map.put("status", 1);//已提交等待审批

        viewList = IbatisTemplate.queryForList("procureExec.queryListExecDetailView", map);
    }

    public List<CateEditDetail> getViewList() {
        return viewList;
    }

    public void setViewList(List<CateEditDetail> viewList) {
        this.viewList = viewList;
    }

    private Person getCurPer() {
        return LoginParam.getPer();
    }

    private Department getCurDept() {
        return LoginParam.getDept();
    }

    private Date getLoginDate() {
        return LoginParam.getLoginDate();
    }

    public CateEditBase getBase() {
        return base;
    }

    public void setBase(CateEditBase base) {
        this.base = base;
    }

    public CateEditDetail getDetail() {
        return detail;
    }

    public void setDetail(CateEditDetail detail) {
        this.detail = detail;
    }

    public DataModel<CateEditDetail> getDetailModel() {
        return detailModel;
    }

    public void setDetailModel(DataModel<CateEditDetail> detailModel) {
        this.detailModel = detailModel;
    }

    public Integer getIyear() {
        return iyear;
    }

    public void setIyear(Integer iyear) {
        this.iyear = iyear;
    }

    public List<Integer> getYearli() {
        return yearli;
    }

    public void setYearli(List<Integer> yearli) {
        this.yearli = yearli;
    }

    public String getQuality() {
        return quality;
    }

    public void setQuality(String quality) {
        this.quality = quality;
    }

    public List<SelectItem> getSelectNameli() {
        return selectNameli;
    }

    public void setSelectNameli(List<SelectItem> selectNameli) {
        this.selectNameli = selectNameli;
    }

    public List<FinancialProject> getProjList() {
        return projList;
    }

    public void setProjList(List<FinancialProject> projList) {
        this.projList = projList;
    }

    public DataModel<FinancialProject> getProjModel() {
        return projModel;
    }

    public void setProjModel(DataModel<FinancialProject> projModel) {
        this.projModel = projModel;
    }

    public boolean isAddOrUpdate() {
        return addOrUpdate;
    }

    public void setAddOrUpdate(boolean addOrUpdate) {
        this.addOrUpdate = addOrUpdate;
    }

    public boolean isEditStatus() {
        return editStatus;
    }

    public void setEditStatus(boolean editStatus) {
        this.editStatus = editStatus;
    }

    public boolean isCheckStatus() {
        return checkStatus;
    }

    public void setCheckStatus(boolean checkStatus) {
        this.checkStatus = checkStatus;
    }

    public List<String> getItemli() {
        return itemli;
    }

    public void setItemli(List<String> itemli) {
        this.itemli = itemli;
    }

    public Category getCate() {
        return cate;
    }

    public void setCate(Category cate) {
        this.cate = cate;
    }

    public FlowInfo getCurrennode() {
        return currennode;
    }

    public void setCurrennode(FlowInfo currennode) {
        this.currennode = currennode;
    }

    public Integer getCurIndex() {
        return curIndex;
    }

    public void setCurIndex(Integer curIndex) {
        this.curIndex = curIndex;
    }

    public List<CateEditDetail> getDetailli() {
        return detailli;
    }

    public void setDetailli(List<CateEditDetail> detailli) {
        this.detailli = detailli;
    }

    public LinkedList<CateEditDetail> getLinkedli() {
        return linkedli;
    }

    public void setLinkedli(LinkedList<CateEditDetail> linkedli) {
        this.linkedli = linkedli;
    }

    public ExecuteAppend getExappend() {
        return exappend;
    }

    public void setExappend(ExecuteAppend exappend) {
        this.exappend = exappend;
    }

    public Integer getIsession() {
        return isession;
    }

    public void setIsession(Integer isession) {
        this.isession = isession;
    }

    public Integer getIsessionFor() {
        return isessionFor;
    }

    public void setIsessionFor(Integer isessionFor) {
        this.isessionFor = isessionFor;
    }
}
